import React, { useState, useEffect } from "react";
import {
  Modal,
  Typography,
  Space,
  Tag,
  Avatar,
  List,
  Button,
  Form,
  Input,
  message,
  Tooltip,
  Divider,
  Alert,
  Dropdown,
  Popconfirm,
} from "antd";
import {
  UserOutlined,
  LikeOutlined,
  LikeFilled,
  RobotOutlined,
  SendOutlined,
  CrownOutlined,
  TeamOutlined,
  BookOutlined,
  DeleteOutlined,
  EditOutlined,
  MoreOutlined,
  FlagOutlined,
  PushpinOutlined,
  MessageOutlined,
  EyeOutlined,
  ClockCircleOutlined,
} from "@ant-design/icons";
import styled from "styled-components";
import type {
  DiscussionPost,
  DiscussionReply,
} from "../../../common/types/discussion";
import { useUser } from "../../../../contexts/UserContext";
import discussionService from "../../../../services/discussion";
import { AIService } from "../../../../services/ai";

const { Title, Text, Paragraph } = Typography;
const { TextArea } = Input;

// 根据用户角色生成默认头像
const getDefaultAvatar = (name: string, role: string) => {
  const hash = name.split('').reduce((a, b) => {
    a = ((a << 5) - a) + b.charCodeAt(0);
    return a & a;
  }, 0);
  const seed = Math.abs(hash).toString();
  
  if (role === "teacher") {
    return `https://api.dicebear.com/7.x/adventurer/svg?seed=${seed}&backgroundColor=b6e3f4`;
  } else {
    return `https://api.dicebear.com/7.x/personas/svg?seed=${seed}&backgroundColor=ffdfbf`;
  }
};

interface DiscussionDetailProps {
  discussionId?: string;
  discussion?: DiscussionPost;
  onClose: () => void;
  likedDiscussions?: Set<string>;
  onLikeChange?: (discussionId: string, isLiked: boolean) => void;
  isTeacher?: boolean;
}

// 教师端专用样式组件
const TeacherStyledModal = styled(Modal)`
  .ant-modal-header {
    background: #1890ff;
    border-bottom: none;
    .ant-modal-title {
      color: white;
      font-weight: 600;
    }
    .ant-modal-close {
      color: white;
      &:hover {
        color: rgba(255, 255, 255, 0.8);
      }
    }
  }
  
  .ant-modal-body {
    max-height: 80vh;
    overflow-y: auto;
    padding: 0;
    background: white;
  }

  .ant-modal-content {
    border-radius: 0;
    overflow: hidden;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  }
`;

const DiscussionContent = styled.div`
  background: white;
  padding: 24px;
  margin-bottom: 0;
  border-bottom: 1px solid #f0f0f0;
`;

const AuthorInfo = styled.div`
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  padding: 12px;
  background: #f5f5f5;
  border-left: 4px solid #1890ff;
`;

const InteractionStats = styled.div`
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 12px 0;
  border-top: 1px solid #f0f0f0;
  margin-top: 16px;
`;

const TeacherReplyList = styled(List<DiscussionReply>)`
  margin-top: 24px;
  
  .ant-list-item {
    padding: 0;
    border: none;
    margin-bottom: 16px;
  }
`;

const ReplyCard = styled.div<{ isTeacher: boolean }>`
  background: ${props => props.isTeacher ? '#1890ff' : 'white'};
  color: ${props => props.isTeacher ? 'white' : '#333'};
  padding: 20px;
  margin-bottom: 16px;
  border: ${props => props.isTeacher ? 'none' : '1px solid #f0f0f0'};
  border-left: ${props => props.isTeacher ? 'none' : '4px solid #52c41a'};
  
  .ant-typography {
    color: ${props => props.isTeacher ? 'white' : '#333'};
  }
  
  .ant-tag {
    background: ${props => props.isTeacher ? 'rgba(255, 255, 255, 0.2)' : '#f0f0f0'};
    color: ${props => props.isTeacher ? 'white' : '#666'};
    border: ${props => props.isTeacher ? '1px solid rgba(255, 255, 255, 0.3)' : '1px solid #d9d9d9'};
  }
`;

const TeacherAIReply = styled.div`
  background: #f0f0f0;
  color: #333;
  padding: 24px;
  margin: 0;
  border-bottom: 1px solid #e0e0e0;
  
  .ant-typography {
    color: #333;
  }
  
  .ant-tag {
    background: #e0e0e0;
    color: #666;
    border: 1px solid #d0d0d0;
  }

  @keyframes blink {
    0%, 50% { opacity: 1; }
    51%, 100% { opacity: 0; }
  }
`;

const ReplyActions = styled.div`
  display: flex;
  align-items: center;
  gap: 12px;
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
`;

const TeacherReplyForm = styled(Form)`
  margin-top: 0;
  background: white;
  padding: 24px;
  border-top: 1px solid #f0f0f0;
  
  .ant-form-item:last-child {
    margin-bottom: 0;
  }
  
  .ant-input {
    border-color: #1890ff;
    
    &:focus {
      border-color: #1890ff;
      box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
    }
  }
  
  .ant-btn-primary {
    background: #1890ff;
    border: none;
    height: 40px;
    font-weight: 500;
    
    &:hover {
      background: #40a9ff;
    }
  }
`;

const TeacherNotice = styled(Alert)`
  margin-bottom: 24px;
  border: 2px solid #1890ff;
  border-radius: 8px;
  .ant-alert-icon {
    color: #1890ff;
  }
`;

const CommentSection = styled.div`
  background: white;
  padding: 24px;
`;

const CommentHeader = styled.div`
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid #f0f0f0;
  
  .ant-typography {
    margin: 0;
    color: #1890ff;
    font-weight: 600;
  }
`;

const DiscussionDetail: React.FC<DiscussionDetailProps> = ({
  discussionId,
  discussion: propDiscussion,
  onClose,
  likedDiscussions = new Set(),
  onLikeChange,
  isTeacher = false,
}) => {
  const { user } = useUser();
  const [discussion, setDiscussion] = useState<DiscussionPost>();
  const [loading, setLoading] = useState(true);
  const [likedReplies, setLikedReplies] = useState<Set<string>>(new Set());
  const [replyForm] = Form.useForm();
  const [aiLoading, setAiLoading] = useState(false);
  const [aiService] = useState(new AIService());
  const [streamingContent, setStreamingContent] = useState("");

  useEffect(() => {
    if (propDiscussion) {
      setDiscussion(propDiscussion);
      setLoading(false);
    } else if (discussionId) {
      loadDiscussion();
    }
  }, [discussionId, propDiscussion]);

  const loadDiscussion = async () => {
    setLoading(true);
    try {
      // 模拟加载讨论详情
      const mockDiscussions: DiscussionPost[] = [
        {
          id: "1",
          title: "如何提高学生的编程实践能力？",
          content: "在教学过程中发现学生的编程实践能力普遍较弱，想请教各位老师有什么好的教学方法可以分享？特别是在数据结构课程中，学生往往理论掌握得不错，但实际编程时遇到很多困难。",
          author: {
            id: "101",
            name: "王建国",
            role: "teacher",
            avatar: getDefaultAvatar("王建国", "teacher")
          },
          createTime: "2024-12-20 14:30:00",
          views: 156,
          likes: 23,
          replies: [
            {
              id: "r1",
              content: "我建议采用项目驱动教学法，让学生在实际项目中应用理论知识。比如设计一个小型管理系统，涵盖链表、栈、队列等数据结构。",
              author: {
                id: "201",
                name: "张伟",
                role: "teacher",
                avatar: getDefaultAvatar("张伟", "teacher")
              },
              createTime: "2024-12-20 15:15:00",
              likes: 15,
              isPinned: false
            },
            {
              id: "r2",
              content: "补充一下，可以让学生结对编程，互相学习。同时设置阶段性检查点，及时发现问题并指导。",
              author: {
                id: "102",
                name: "王雅琴",
                role: "student",
                avatar: getDefaultAvatar("王雅琴", "student")
              },
              createTime: "2024-12-20 16:20:00",
              likes: 8,
              isPinned: false
            }
          ],
          tags: ["教学方法", "编程实践", "能力培养"],
          isPinned: true,
          aiResponse: {
            content: "基于您的问题，我建议从以下几个方面来提升学生的编程实践能力：\n\n**1. 项目驱动教学**\n- 设计贴近实际的小项目，如学生管理系统\n- 分阶段实施，每个阶段对应不同的数据结构\n- 设置明确的验收标准和检查点\n\n**2. 实践环境优化**\n- 提供在线编程平台，如LeetCode、牛客网\n- 建立代码仓库，方便学生查看优秀代码\n- 使用版本控制工具，培养工程化思维\n\n**3. 教学方法改进**\n- 采用翻转课堂，课前预习，课上实践\n- 实施同伴学习，结对编程\n- 定期举办编程竞赛，激发学习兴趣\n\n**4. 评价体系完善**\n- 过程性评价与结果性评价相结合\n- 重视代码质量和编程规范\n- 鼓励创新思维和问题解决能力",
            createTime: "2024-12-20 16:00:00"
          }
        },
        {
          id: "2",
          title: "数据结构中链表和数组的区别是什么？",
          content: "在学习数据结构时，我对链表和数组的区别有些困惑。链表和数组在内存分配、访问效率、插入删除操作等方面有什么不同？希望有经验的同学能分享一下。",
          author: {
            id: "103",
            name: "陈志强",
            role: "student",
            avatar: getDefaultAvatar("陈志强", "student")
          },
          createTime: "2024-12-19 10:45:00",
          views: 89,
          likes: 12,
          replies: [
            {
              id: "r3",
              content: "链表和数组的主要区别在于内存分配方式。数组是连续存储，链表是离散存储。数组访问效率高但插入删除慢，链表相反。",
              author: {
                id: "202",
                name: "李雅琴",
                role: "teacher",
                avatar: getDefaultAvatar("李雅琴", "teacher")
              },
              createTime: "2024-12-19 11:30:00",
              likes: 18,
              isPinned: true
            }
          ],
          tags: ["数据结构", "算法", "链表"],
          isPinned: false,
          aiResponse: undefined
        }
      ];

      const discussion = mockDiscussions.find(d => d.id === discussionId);
      if (discussion) {
        setDiscussion(discussion);
      } else {
        message.error("讨论不存在");
      }
    } catch (error) {
      message.error("加载讨论详情失败");
      console.error("加载讨论详情失败:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleLike = async () => {
    if (!discussion) return;
    
    try {
      const isLiked = likedDiscussions.has(discussion.id);
      
      // 更新讨论点赞数
      setDiscussion({
        ...discussion,
        likes: isLiked ? discussion.likes - 1 : discussion.likes + 1
      });
      
      // 通知父组件更新点赞状态
      if (onLikeChange) {
        onLikeChange(discussion.id, !isLiked);
      }
      
      message.success(isLiked ? "取消点赞成功！" : "点赞成功！");
    } catch (error) {
      message.error("操作失败，请重试");
      console.error("点赞操作失败:", error);
    }
  };

  const handleReplyLike = async (replyId: string) => {
    if (!discussion) return;
    
    try {
      const newLikedReplies = new Set(likedReplies);
      const isLiked = newLikedReplies.has(replyId);
      
      if (isLiked) {
        newLikedReplies.delete(replyId);
      } else {
        newLikedReplies.add(replyId);
      }
      setLikedReplies(newLikedReplies);

      // 更新回复点赞数
      const updatedReplies = discussion.replies.map(reply => 
        reply.id === replyId 
          ? { ...reply, likes: isLiked ? reply.likes - 1 : reply.likes + 1 }
          : reply
      );
      
      setDiscussion({
        ...discussion,
        replies: updatedReplies
      });
      
      message.success(isLiked ? "取消点赞成功！" : "点赞成功！");
    } catch (error) {
      message.error("点赞失败，请重试");
      console.error("点赞失败:", error);
    }
  };

  const handleRegenerateAIResponse = async () => {
    if (!discussion) return;

    setAiLoading(true);
    setStreamingContent(""); // 清空流式内容
    
    try {
      // 构建更专业的AI提示词
      const enhancedPrompt = `作为一位资深的教育专家，请针对以下教学讨论提供专业的分析和建议：

**讨论主题：** ${discussion.title}
**讨论内容：** ${discussion.content}
**讨论标签：** ${discussion.tags.join('、')}

请从以下角度进行分析：
1. 教学策略建议
2. 学生能力培养方法
3. 实践应用指导
4. 常见问题解决方案

请提供具体、可操作的建议，帮助教师改进教学方法。`;

      // 先创建一个空的AI回复，用于流式显示
      const tempAiResponse = {
        content: "",
        createTime: new Date().toISOString()
      };

      setDiscussion({
        ...discussion,
        aiResponse: tempAiResponse
      });

      // 流式处理AI回复
      const response = await aiService.generateResponse(
        {
          ...discussion,
          enhancedPrompt
        },
        (chunk: string) => {
          // 流式更新内容
          setStreamingContent(prev => prev + chunk);
          
          // 同时更新讨论中的AI回复内容
          setDiscussion(prev => {
            if (!prev) return prev;
            return {
              ...prev,
              aiResponse: {
                ...prev.aiResponse!,
                content: prev.aiResponse!.content + chunk
              }
            };
          });
        }
      );

      // 流式完成后，确保最终内容正确
      setDiscussion(prev => {
        if (!prev) return prev;
        return {
          ...prev,
          aiResponse: {
            ...prev.aiResponse!,
            content: response
          }
        };
      });

      setStreamingContent(""); // 清空流式内容
      message.success("AI智能分析已重新生成");
    } catch (error) {
      message.error("AI分析生成失败，请检查网络连接后重试");
      console.error("AI回复生成失败:", error);
    } finally {
      setAiLoading(false);
    }
  };

  const handleReply = async () => {
    if (!discussion) return;
    
    try {
      const values = await replyForm.validateFields();
      const newReply: DiscussionReply = {
        id: `reply_${Date.now()}`,
        content: values.reply,
        author: {
          id: user?.id || "current_teacher",
          name: user?.name || "当前教师",
          role: "teacher",
          avatar: getDefaultAvatar(user?.name || "当前教师", "teacher")
        },
        createTime: new Date().toISOString(),
        likes: 0,
        isPinned: false
      };

      setDiscussion({
        ...discussion,
        replies: [...discussion.replies, newReply]
      });

      replyForm.resetFields();
      message.success("回复成功！");
    } catch (error) {
      message.error("回复失败，请重试");
      console.error("回复失败:", error);
    }
  };

  // 教师管理功能
  const handleDeleteReply = (replyId: string) => {
    if (!discussion) return;
    
    Modal.confirm({
      title: "确认删除回复",
      content: "删除后将无法恢复，是否确认删除？",
      okText: "确认删除",
      cancelText: "取消",
      okType: "danger",
      onOk: () => {
        setDiscussion({
          ...discussion,
          replies: discussion.replies.filter(reply => reply.id !== replyId)
        });
        message.success("回复已删除");
      }
    });
  };

  const handlePinReply = (replyId: string) => {
    if (!discussion) return;
    
    const updatedReplies = discussion.replies.map(reply => 
      reply.id === replyId 
        ? { ...reply, isPinned: !reply.isPinned }
        : reply
    );
    
    setDiscussion({
      ...discussion,
      replies: updatedReplies
    });
    
    const reply = discussion.replies.find(r => r.id === replyId);
    message.success(reply?.isPinned ? "取消置顶成功" : "置顶回复成功");
  };

  const handleFlagReply = (replyId: string) => {
    message.success("回复已标记为重要");
  };

  const handleDeleteDiscussion = () => {
    if (!discussion) return;
    
    Modal.confirm({
      title: "确认删除讨论",
      content: "删除后将无法恢复，是否确认删除？",
      okText: "确认删除",
      cancelText: "取消",
      okType: "danger",
      onOk: () => {
        onClose();
        message.success("讨论已删除");
      }
    });
  };

  const handlePinDiscussion = () => {
    if (!discussion) return;
    
    setDiscussion({
      ...discussion,
      isPinned: !discussion.isPinned
    });
    message.success("置顶状态已更新");
  };

  if (!discussion) {
    return null;
  }

  const isLiked = likedDiscussions.has(discussion.id);

  return (
    <TeacherStyledModal
      title={
        <Space>
          {discussion.author.role === "teacher" ? <CrownOutlined /> : <TeamOutlined />}
          <span>讨论详情</span>
          {discussion.author.role === "teacher" && (
            <Tag icon={<CrownOutlined />} color="gold">教师</Tag>
          )}
          {isTeacher && (
            <Dropdown
              menu={{
                items: [
                  {
                    key: "pin",
                    label: discussion.isPinned ? "取消置顶" : "置顶",
                    icon: <PushpinOutlined />,
                    onClick: handlePinDiscussion
                  },
                  {
                    key: "regenerate",
                    label: "重新生成AI回复",
                    icon: <RobotOutlined />,
                    onClick: handleRegenerateAIResponse,
                    disabled: !discussion.aiResponse
                  },
                  {
                    type: "divider" as const
                  },
                  {
                    key: "delete",
                    label: "删除讨论",
                    icon: <DeleteOutlined />,
                    danger: true,
                    onClick: handleDeleteDiscussion
                  }
                ]
              }}
              trigger={["click"]}
              placement="bottomRight"
            >
              <Button type="text" icon={<MoreOutlined />} style={{ color: "white" }} />
            </Dropdown>
          )}
        </Space>
      }
      open={!!discussionId}
      onCancel={onClose}
      width={1000}
      footer={null}
    >
      {loading ? (
        <div style={{ textAlign: "center", padding: "40px" }}>
          <div>加载中...</div>
        </div>
      ) : (
        <div>
          {/* 讨论内容 */}
          <DiscussionContent>
            <Title level={3} style={{ marginBottom: 20, color: '#1890ff' }}>
              {discussion.title}
            </Title>
            
            <AuthorInfo>
              <Avatar
                src={discussion.author.avatar}
                icon={<UserOutlined />}
                size={48}
                style={{
                  backgroundColor: discussion.author.role === "teacher" ? "#1890ff" : "#52c41a",
                  marginRight: 12
                }}
              />
              <div style={{ flex: 1 }}>
                <div style={{ marginBottom: 4 }}>
                  <Text strong style={{ fontSize: 16 }}>{discussion.author.name}</Text>
                  {discussion.author.role === "teacher" && (
                    <Tag icon={<CrownOutlined />} color="gold" style={{ marginLeft: 8 }}>
                      教师
                    </Tag>
                  )}
                </div>
                <Text type="secondary" style={{ 
                  fontSize: 12, 
                  color: '#999',
                  display: 'flex',
                  alignItems: 'center',
                  gap: 4
                }}>
                  <ClockCircleOutlined style={{ fontSize: 12 }} />
                  {new Date(discussion.createTime).toLocaleString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit'
                  })}
                </Text>
              </div>
            </AuthorInfo>
            
            <Paragraph style={{ fontSize: 15, lineHeight: 1.8, marginBottom: 16 }}>
              {discussion.content}
            </Paragraph>
            
            <Space wrap>
              {discussion.tags.map((tag) => (
                <Tag key={tag} color="blue" style={{ padding: '4px 12px', borderRadius: 6 }}>
                  {tag}
                </Tag>
              ))}
            </Space>
            
            <InteractionStats>
              <Button
                type={isLiked ? "primary" : "default"}
                icon={isLiked ? <LikeFilled /> : <LikeOutlined />}
                onClick={handleLike}
                style={{ 
                  borderRadius: 8,
                  background: isLiked ? 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)' : undefined
                }}
              >
                {discussion.likes} 点赞
              </Button>
              <Text type="secondary" style={{ fontSize: 14 }}>
                <EyeOutlined style={{ marginRight: 4 }} />
                浏览 {discussion.views}
              </Text>
              <Text type="secondary" style={{ fontSize: 14 }}>
                <MessageOutlined style={{ marginRight: 4 }} />
                回复 {discussion.replies.length}
              </Text>
            </InteractionStats>
          </DiscussionContent>

          {/* AI回复 */}
          <TeacherAIReply>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <RobotOutlined style={{ fontSize: 18, color: '#1890ff' }} />
                <Text strong style={{ fontSize: 16 }}>AI智能分析</Text>
                {discussion.aiResponse?.createTime && (
                  <Text type="secondary" style={{ 
                    fontSize: 12, 
                    color: '#999',
                    display: 'flex',
                    alignItems: 'center',
                    gap: 4
                  }}>
                    <ClockCircleOutlined style={{ fontSize: 12 }} />
                    {new Date(discussion.aiResponse.createTime).toLocaleString('zh-CN', {
                      year: 'numeric',
                      month: '2-digit',
                      day: '2-digit',
                      hour: '2-digit',
                      minute: '2-digit'
                    })}
                  </Text>
                )}
              </div>
              {isTeacher && (
                <Button
                  type="primary"
                  size="small"
                  loading={aiLoading}
                  onClick={handleRegenerateAIResponse}
                  icon={<RobotOutlined />}
                  style={{ 
                    background: '#1890ff',
                    border: 'none',
                    borderRadius: 6,
                    height: 32,
                    padding: '0 16px',
                    fontWeight: 500
                  }}
                >
                  {discussion.aiResponse ? '重新生成AI回复' : '生成AI回复'}
                </Button>
              )}
            </div>
            <Paragraph style={{ 
              marginBottom: 0, 
              lineHeight: 1.8,
              fontSize: 14,
              color: '#333'
            }}>
              {aiLoading && streamingContent ? (
                <span>
                  {streamingContent}
                  <span style={{ 
                    animation: 'blink 1s infinite',
                    color: '#1890ff'
                  }}>|</span>
                </span>
              ) : (
                discussion.aiResponse?.content || <span style={{ color: '#bbb' }}>暂无AI智能分析，可点击右上角按钮生成</span>
              )}
            </Paragraph>
          </TeacherAIReply>

          {/* 回复列表 */}
          <CommentSection>
            <CommentHeader>
              <Title level={4}>评论区 ({discussion.replies.length})</Title>
            </CommentHeader>
            
            {discussion.replies
              .sort((a, b) => (b.isPinned ? 1 : 0) - (a.isPinned ? 1 : 0))
              .map((reply) => {
                const isReplyLiked = likedReplies.has(reply.id);
                const replyMenuItems = isTeacher ? [
                  {
                    key: "pin",
                    label: reply.isPinned ? "取消置顶" : "置顶回复",
                    icon: <PushpinOutlined />,
                    onClick: () => handlePinReply(reply.id)
                  },
                  {
                    key: "flag",
                    label: "标记重要",
                    icon: <FlagOutlined />,
                    onClick: () => handleFlagReply(reply.id)
                  },
                  {
                    type: "divider" as const
                  },
                  {
                    key: "delete",
                    label: "删除回复",
                    icon: <DeleteOutlined />,
                    danger: true,
                    onClick: () => handleDeleteReply(reply.id)
                  }
                ] : [];

                return (
                  <ReplyCard key={reply.id} isTeacher={reply.author.role === "teacher"}>
                    <div style={{ display: 'flex', alignItems: 'flex-start', marginBottom: 12 }}>
                      <Avatar
                        src={reply.author.avatar}
                        icon={<UserOutlined />}
                        size={40}
                        style={{
                          backgroundColor: reply.author.role === "teacher" ? "#1890ff" : "#52c41a",
                          marginRight: 12
                        }}
                      />
                      <div style={{ flex: 1 }}>
                        <div style={{ display: 'flex', alignItems: 'center', marginBottom: 8 }}>
                          <Text strong style={{ fontSize: 14, marginRight: 8 }}>
                            {reply.author.name}
                          </Text>
                          {reply.author.role === "teacher" && (
                            <Tag icon={<CrownOutlined />} color="gold" style={{ marginRight: 8 }}>
                              教师
                            </Tag>
                          )}
                          {reply.isPinned && (
                            <Tag icon={<PushpinOutlined />} color="blue" style={{ marginRight: 8 }}>
                              置顶
                            </Tag>
                          )}
                          <Text type="secondary" style={{ 
                            fontSize: 12, 
                            color: '#999',
                            display: 'flex',
                            alignItems: 'center',
                            gap: 4
                          }}>
                            <ClockCircleOutlined style={{ fontSize: 12 }} />
                            {new Date(reply.createTime).toLocaleString('zh-CN', {
                              year: 'numeric',
                              month: '2-digit',
                              day: '2-digit',
                              hour: '2-digit',
                              minute: '2-digit'
                            })}
                          </Text>
                          {isTeacher && replyMenuItems.length > 0 && (
                            <Dropdown
                              menu={{ items: replyMenuItems }}
                              trigger={["click"]}
                              placement="bottomRight"
                            >
                              <Button 
                                type="text" 
                                size="small" 
                                icon={<MoreOutlined />}
                                style={{ marginLeft: 'auto' }}
                              />
                            </Dropdown>
                          )}
                        </div>
                        
                        <Paragraph style={{ marginBottom: 12, lineHeight: 1.6 }}>
                          {reply.content}
                        </Paragraph>
                        
                        <ReplyActions>
                          <Button
                            type={isReplyLiked ? "primary" : "text"}
                            size="small"
                            icon={isReplyLiked ? <LikeFilled /> : <LikeOutlined />}
                            onClick={() => handleReplyLike(reply.id)}
                            style={{ 
                              color: isReplyLiked ? 'white' : undefined,
                              border: 'none',
                              padding: '4px 8px'
                            }}
                          >
                            {reply.likes}
                          </Button>
                          {isTeacher && (
                            <Button
                              type="text"
                              size="small"
                              icon={<MessageOutlined />}
                              style={{ 
                                color: reply.author.role === "teacher" ? 'white' : undefined,
                                border: 'none',
                                padding: '4px 8px'
                              }}
                            >
                              回复
                            </Button>
                          )}
                        </ReplyActions>
                      </div>
                    </div>
                  </ReplyCard>
                );
              })}
          </CommentSection>

          {/* 回复表单 */}
          <TeacherReplyForm form={replyForm}>
            <Form.Item
              name="reply"
              rules={[
                { required: true, message: "请输入回复内容" },
                { min: 5, message: "回复内容至少5个字符" },
              ]}
            >
              <TextArea
                rows={4}
                placeholder={isTeacher ? "作为教师，您可以提供专业的教学建议和解答..." : "请输入您的回复..."}
              />
            </Form.Item>
            <Form.Item>
              <Button
                type="primary"
                icon={<SendOutlined />}
                onClick={handleReply}
                style={{
                  background: "linear-gradient(135deg, #667eea 0%, #764ba2 100%)",
                  border: "none"
                }}
              >
                发表回复
              </Button>
            </Form.Item>
          </TeacherReplyForm>
        </div>
      )}
    </TeacherStyledModal>
  );
};

export default DiscussionDetail; 